﻿using CircuitBreaker;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Random r = new Random(1);
            int counter = 0;

            //int subfix = r.Next(5);
            //string name = "cb" + subfix;
            //CircuitBreakerSettings settings = new CircuitBreakerSettings(name, 5, 5, 500);
            //CircuitBreaker.CircuitBreaker cb = CircuitBreakerFactory.GetCircuitBreaker(settings);

            bool openCircuitBreaker = false;
            Parallel.For(0, 200, i =>
            {
                int innerCounter = Interlocked.Increment(ref counter);
                Thread.Sleep(100);
                int subfix = r.Next(5);
                string name = "cb" + subfix;
                CircuitBreakerSettings settings = new CircuitBreakerSettings(name, 5, 5, 500);
                CircuitBreaker.CircuitBreaker cb = CircuitBreakerFactory.GetCircuitBreaker(settings);
                 if (innerCounter%10==0)
                {

                    openCircuitBreaker = !openCircuitBreaker;
                    Console.WriteLine("time to exchange circuit breaker status to "+(openCircuitBreaker ?"open":"close"));
                }
                try
                {
                    cb.AttemptCall(() =>
                           {
                               if (openCircuitBreaker)
                               {
                                   throw new Exception(cb.Name + ": let's fail it");
                               }
                               else
                               {
                                   Console.WriteLine(cb.Name + ": you'v passed");
                               }
                           });
                }
                catch (OpenCircuitException)
                {
                    Console.WriteLine(cb.Name + ": failed due to circuit break");
                }
                catch (NullReferenceException ex)
                {
                    Console.WriteLine(ex);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            });
            Console.ReadLine();
        }
    }
}
